<?php
function shortIp($ip) {
    $shortNotation = 0;
    $parts = explode('.', $ip);
    $multiplier = 1;
    for ($i = count($parts) -1; $i >= 0; $i--) {
        $shortNotation += $parts[$i] * $multiplier;
        $multiplier *= 256;
    }
    return $shortNotation;
}

function countryCodeByIP($ip) {
    $ip = shortIp($ip);
    $countryCode = false;
 
    $db = new PDO('sqlite:Counter.db');
    
    $query = $db->query("SELECT CountryCode FROM IpRanges WHERE RangeStart <= " . $ip . " AND RangeEnd >= " . $ip);
    if ($query) {
        $entry = $query->fetchObject();
        if ($entry) {
            $countryCode = $entry->CountryCode;
        }
    }
    $db = NULL;
    
    return $countryCode;
}
